#!/usr/bin/python -O

import server

import os
import sys
import asyncore
import weakref
import pyPopeye_access
import ConfigParser

srv_conf = "servers.conf"


class pyPopeye(object):
    def __init__(self, servers):
        
        self.servers = []
        for i in servers:
            i['ssl'] = False
            port = i.pop('port', '6667')
            if port.startswith('+'):
                port = port[1:]
                i['ssl'] = True
            port = int(port)
            
            srv = server.server(i.pop('server'), port, i, weakref.ref(self))
            
            self.servers.append(srv)
    
    def reconnect(self, reconn_server):
        print "[-- RECONNECTING %s --]" % reconn_server.server_host
        i = self.servers.index(reconn_server)
        reconn_server.writeln('QUIT :reconnecting')
        del self.servers[i]
        host = reconn_server.server_host
        port = reconn_server.port
        conn_info = reconn_server.conn_info
        
        del reconn_server
        
        self.servers += [server.server(host, port, conn_info, weakref.ref(self))]
    
    def quit(self):
        for i in self.servers:
            i.quit()
        raise SystemExit
    
if __name__ == '__main__':
    cfg = ConfigParser.ConfigParser()
    cfg.read(srv_conf)
    servers = []

    for i in cfg.sections():
        #skip the access section, it's not a server
        if i == 'access':
            continue
        servers += [dict(cfg.items(i))]
    
    p = pyPopeye(servers)
    try:
        asyncore.loop()
    except:
        print 'Exited via keyboard interrupt'
